﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using CommunityToolkit.Mvvm.Input;

namespace PkwDevFramework.WpfMvvm
{
    /// <summary>
    /// 导航窗体ViewModel
    /// </summary>
    public class NavViewModel : BaseViewModel
    {
        /// <summary>
        ///
        /// </summary>
        public string ViewNamespace { get; set; }

        #region 基础属性

        private FrameworkElement _currentPage;

        /// <summary>
        /// 页面主体
        /// </summary>
        public FrameworkElement CurrentPage
        {
            get { return _currentPage; }
            set { SetProperty(ref _currentPage, value); }
        }

        /// <summary>
        /// 导航按钮集合
        /// </summary>
        public List<NavigationButton> NavigationButtons { get; set; }

        #endregion


        #region 命令

        public ICommand ChangePageCommand
        {
            get =>
                new RelayCommand<object>(obj =>
                {
                    ChangePage(obj as string);
                });
        }

        #endregion


        public NavViewModel()
        {
            NavigationButtons = new List<NavigationButton>();

            Init();
        }

        public virtual void Init() { }

        /// <summary>
        /// 页面跳转
        /// </summary>
        /// <param name="model"></param>
        protected void ChangePage(string pageName)
        {
            //对旧页面进行取消激活操作
            if (CurrentPage != null && CurrentPage.DataContext is PageViewModel old)
            {
                old.PageInactived(this, new EventArgs());
            }

            CurrentPage = GetPage(pageName);
            if (CurrentPage == null)
            {
                CurrentPage = new TextBlock { Text = "页面不存在" };
                return;
            }
            //对新页面进行激活操作
            if (CurrentPage.DataContext is PageViewModel viewModel)
            {
                viewModel.PageActiving(this, new EventArgs());
            }
        }

        /// <summary>
        /// 获取页面
        /// </summary>
        /// <param name="pageName">页面名称</param>
        /// <returns></returns>
        protected FrameworkElement GetPage(string pageName)
        {
            foreach (var item in NavigationButtons)
            {
                item.IsChecked = false;
            }
            var btn = NavigationButtons.FirstOrDefault(x => x.CommandParameter == pageName);
            if (btn != null)
            {
                btn.IsChecked = true;
            }

            Type type = this.GetType().Assembly.GetType($"{ViewNamespace}.{pageName}");
            if (type == null)
            {
                return null;
            }
            return (FrameworkElement)Activator.CreateInstance(type);
        }
    }
}
